import { Component, OnInit, Injector, Output, EventEmitter, Input } from '@angular/core';
import { Service } from '../../../server/server';
import { CudTableService } from '../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../public/serve/init/init.service';
import { BaseTreeComponent } from '../../../public/components/base-tree/base-tree.component';
import { HttpClient } from '@angular/common/http';
import { TreeNode } from '../../../public/common/api';
import { tokenName, ThrowStmt } from '@angular/compiler';
import { DatePipe } from '@angular/common';

declare var $:any;
@Component({
  selector: 'app-add-keyword',
  templateUrl: './add-keyword.component.html',
  styleUrls: ['./add-keyword.component.css']
})
export class AddKeywordComponent implements OnInit {

  l_pageNo :number = 1;
  l_pageSize      : number = 20;
  l_total: number = 0;
  l_naturalNum: number = 0;

  r_pageNo :number = 1;
  r_pageSize      : number = 20;
  r_total: number = 0;
  r_naturalNum: number = 0;

  treeData      : TreeNode[];
  selectedData  : TreeNode[];
  selectedFile  : TreeNode[];
  @Input() searchData: any;
  @Input() themeName :any = '';
  @Input() themeCode:any = '';
  @Input() internalParam : any;
  loading: boolean = false;

  parentid : any = '';
  themeTableId : any;//主题词表id
  themeTableName:any;//主题词表名称
  nodeDate:any;//点击当前的节点数据

  result = [];
  treeDataScroll = [];
  previousActive : boolean = false;//上一页
  nextActive : boolean = false;//下一页
  totalPage :number;

  constructor(
    private server: Service,
    public request: CudTableService,
    private tableListService: CudTableService,
    private hintsService: HintsService,
    private removeTableService: RemoveTableService,
    public initService: InitService,
    private datePipe: DatePipe,
    private http: HttpClient
  ) { }

  ngOnInit() {
    if(this.r_pageNo == 1){
      this.previousActive = false;
      this.nextActive = true;
    }
  }

  _infoScroll(){
    this.r_pageNo = 1;
    this.result = [];
    this.treeDataScroll = [];
    this.treeData = [];
    this.nodeDate = '';
  }

  //下一页
  onScrollDown(){
    this.totalPage  = Math.ceil(this.r_total/  this.r_pageSize);

    if(this.r_pageNo < this.totalPage){
      this.r_pageNo += 1;
      this.previousActive = true;
      this.nextActive = true;
      this._keywordTree(this.nodeDate);
    }

    if(this.r_pageNo == this.totalPage){
      this.previousActive = true;
      this.nextActive = false;
    }
  }


  //上一页
  onScrollUp(){
    
    if(this.r_pageNo > 1){
      this.r_pageNo -= 1;
      this.nextActive = true;
      this._keywordTree(this.nodeDate);
    }
    if(this.r_pageNo == 1){
      this.previousActive = false;
    } 
    
  }

  /**
   * 
   * 查询任务已分配的主题词表的主题词列表
   * 树状图
   */ 
  _keywordTree(node:any='') {
    //this.loading = true;
    this.themeTableName = this.internalParam.themeTableName;//当前主题词表的名称
    let data = {
      token         : 'b25dbd7138cf48e09941087e6d9a2e93',
      themeTableId  : this.internalParam.themeTableId,
      pageNo        : this.r_pageNo,
      pageSize      : this.r_pageSize,
      checkStatus   : 1,
    };
    this.request.postRequest( this.server.baseUrl + 'Service/ThemeWords/getThemeWordsList',data).then((res:any) => {
     
      if (res.result_code === '0000') {
        this.treeData = res.result;
        this.r_naturalNum = res.length;
        this.r_total = res.length;
        //加最顶级（当前主题词表的名称）
        let tmp = {
          id:'',
          label:  this.themeTableName,
          data:  this.themeTableName,
          children: []
        };

        if(this.treeData.length > 0){
          this.treeData = this._processTreeData(this.treeData,'themeWordsId','parentid','name');
          for(let i=0;i < this.treeData.length;++i){
            this.result.push(this.treeData[i]);
          }
          this.treeDataScroll = [...this.result];

          if(node){
            this.selectedFile = [...[node]];
          }else{
            // 默认选中第一个节点（注释部分为：展开第一个节点）
            this.selectedFile = [...[tmp]];
            //默认加载第一个
            this.parentid = '';
          }
          
          tmp.children = this.treeDataScroll;
        }else{
          this.parentid = '';
          this.selectedFile = [...[tmp]];
        }
        let tmpArr = [];
        tmpArr.push(tmp);
        this.treeDataScroll = tmpArr;

        // 展开所有节点
        this._expandAll();
        this._leftThemeWord();
      }else{
        this.hintsService.messages(res.message,res.result_code);
      }
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  /**
   * 分页
   * @param pagination 
   */ 
  r_pagination(pagination: Array<any>) {
    this.r_pageNo = pagination[0].pageNumber;
    this.r_pageSize   = pagination[0].pageSize;
    this.r_naturalNum = (this.r_pageNo - 1) * this.r_pageSize;
    this._keywordTree(this.nodeDate);
  }
  /**
   * 分页
   * @param pagination 
   */ 
  l_pagination(pagination: Array<any>) {
    this.l_pageNo = pagination[0].pageNumber;
    this.l_pageSize   = pagination[0].pageSize;
    this.l_naturalNum = (this.r_pageNo - 1) * this.l_pageSize;
    this._leftThemeWord();
  }

  /**
   * 选中的节点
   * @param event 
   * @param id 
   */
  _nodeSelect(event) {
    this.selectedData = [];
    this.parentid = event.node.id;
    this.nodeDate = event.node;
    this._leftThemeWord();
  }

  /**
   * 
   */
  _leftThemeWord(){
    let data = {
      token         : 'b25dbd7138cf48e09941087e6d9a2e93',
      themeTableId  : this.internalParam.themeTableId,
      pageNo        : this.l_pageNo,
      pageSize      : this.l_pageSize,
      checkStatus   : 1,
      parentId      : this.parentid,
      queryCriteria : this.searchData
    };
    this.request.postRequest( this.server.baseUrl + 'Service/ThemeWords/getThemeWordsList',data).then((res:any) => {
      
      if (res.result_code === '0000') {
        this.selectedData = res.result;
        this.l_naturalNum = res.length;
        this.l_total = res.length;
      }else{
        this.hintsService.messages(res.message,res.result_code);
      }

      //this.loading = false;
      return;
    })
    .catch((err: any)=>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  //查询
  search() {
    this._leftThemeWord();
  }
  //响应搜索
  changesearch() {
      this.search();
  }

  _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
    return this._toTree(list, '0', idName,parentIdName,labelName);
  }

  _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
    let idKey = idName;
    let result = [];
    
    for (let item of list) {
       
        if (item[parentIdName] == topId) {

          let children = this._toTree(list, item[idKey], idName, parentIdName, labelName)
             if (children && children.length > 0) {
                 item.children = children;
           } 
           
           let dataArr = {
            id:item['themeWordsId'],
            label: item['name'],
            data: item['name'],
            createBy:item['createBy'],
            createTime : item['createTime'],
            status : item['status'],
            arrchildid:item['arrchildid'],
            arrparentid:item['arrparentid'],
            themeTableId:item['themeTableId'],
            themeWordsId:item['themeWordsId'],
            parentid:item['parentid'],
            children:children
          };

          result.push(dataArr);
        }
    }
    return result;
  }

  /**
   * 展开所有树节点
   */
  private _expandAll() {
    this.treeDataScroll.forEach(node => {
      this.expandRecursive(node, true);
    });
  }

  // 递归
  private expandRecursive(node: TreeNode, isExpand: boolean) {
    node.expanded = isExpand;
    if (node.hasOwnProperty('childProductTypeVoList')) {
      node.children = node['childProductTypeVoList'];
      node.children.forEach(childNode => {
        this.expandRecursive(childNode, isExpand);
      });
    }
  }

  /**
   * 新增主题词
   */
  _addThemeWord(){
    let data = {};
    data['token'] = 'b25dbd7138cf48e09941087e6d9a2e93';
    data['createBy'] = this.server.getuserName();
    data['createTime'] = this.datePipe.transform(new Date(), 'yyyy-MM-dd HH:mm:ss');
    data['checkStatus'] = 1;//是否审核  默认是未审核=0，已审核=1
    data['child'] = 0;
    data['themeTableId'] = this.internalParam.themeTableId;
    data['themeGroupId'] = this.internalParam.themeGroupId;
    data['parentId'] = this.parentid;
    data['name'] = this.themeName;
    data['themeCode'] = this.themeCode;
    data['status'] = 0;
    data['description'] = this.themeName;
    let url = this.server.baseUrl + 'Service/ThemeWords/addThemeWords';
    this.request
    .postRequest(url,data)
    .then(res =>{
      if(res.result_code === "0000"){
        this._infoAdd();
        this._keywordTree(this.nodeDate);
      }

      this.hintsService.messages(res.message,res.result_code);
      return;
    })
    .catch(err =>{
      this.hintsService.messages("error","error");
      return;
    });
  }

  _infoAdd(){
    this.r_pageNo = 1;
    this.result = [];
    this.treeDataScroll = [];
    this.treeData = [];
    this.themeName = '';
    this.themeCode = '';
  }

  /**
   * 判断是否为空数组
   */ 
  _isNameEmpty() {
    // || this.themeCode == ''
    if (this.themeName == '') {
      return true;
    }
    return false;
  }

  //删除主题词
  _deleteTheme(val:any){
    let id = val.themeWordsId;
    this.removeTableService.getRemoveTableId = [];
    this.removeTableService.keywordRemoveChose(true, id, 1)['bool'];

    let url = this.server.baseUrl + 'Service/ThemeWords/deleteThemeWords';
    this.removeTableService
    .confirmRemove('ids',url,'token','b25dbd7138cf48e09941087e6d9a2e93')
    .then(res => {
      if(res.result_code == '0000'){
        this._leftThemeWord();
      }

      this.hintsService.messages(res.message,res.result_code);
      return;
    })
    .catch(err => {
      this.hintsService.messages('error','error');
      return;
    });
  }

}
